const response = require('./response')
const jwt = require("jsonwebtoken");
const { AUTH, NOTOKENPATH } = require('../config/constants')
// 生成JWT令牌
const sign = (data, usefulTime = AUTH.EXPIRES_IN) => {
    return jwt.sign(data, AUTH.SECRET, { expiresIn: usefulTime });
};
// 验证JWT令牌中间件
const verify = async (ctx, next) => {
    // 白名单路径直接放行
    if (NOTOKENPATH.includes(ctx.path)) {
        return await next();
    }
    // 获取并验证Authorization头
    const authHeader = ctx.headers.authorization;

    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return response.error(ctx, {
            message: '无有效认证令牌',
            status: 401
        });
    }

    try {
        const decoded = jwt.verify(authHeader.split(' ')[1], AUTH.SECRET);
        console.log(decoded)
        ctx.userId = decoded.id; // 设置用户ID到上下文
        await next();
    } catch (err) {
        const errorMessage = err.name === 'TokenExpiredError'
            ? '认证令牌已过期'
            : err || '无效的认证令牌';
        return response.error(ctx, {
            message: errorMessage,
            status: 401
        });
    }
};

const isVerify = (ctx) => {
    // 获取并验证Authorization头
    const authHeader = ctx.headers.authorization;
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
        return {
            message: '无有效认证令牌',
            status: 401
        }
    }
    const token = authHeader.split(' ')[1];
    try {
        const decoded = jwt.verify(token, AUTH.SECRET);
        ctx.userId = decoded.id; // 设置用户ID到上下文
        return {
            message: 'success',
            status: 200
        }
    } catch (err) {
        const errorMessage = err.name === 'TokenExpiredError'
            ? '认证令牌已过期'
            : '无效的认证令牌';

        return {
            message: errorMessage,
            status: 401
        }
    }
};

module.exports = {
    sign,
    verify,
    isVerify
};
